#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <vector>
#include<string>
using namespace std;

pthread_mutex_t gmutex=PTHREAD_MUTEX_INITIALIZER;//全局互斥锁
pthread_cond_t gcond=PTHREAD_COND_INITIALIZER;//全局条件变量

void *SlaverCore(void *args)
{
    std::string name = static_cast<const char*>(args);
    while(true)
    {
        pthread_mutex_lock(&gmutex);//加锁
        pthread_cond_wait(&gcond,&gmutex);//等待条件变量被信号量唤醒，同时解锁互斥锁
        std::cout<<"当前被叫醒的线程是："<<name<<std::endl;
        pthread_mutex_unlock(&gmutex);//解锁
    }
}

void *MasterCore(void *args)
{
    sleep(3);//等待所有子线程先加锁
    std::string name = static_cast<const char*>(args);
    while(true)
    {
        //pthread_cond_signal(&gcond);//发送信号量，唤醒一个等待的线程
        //std::cout<<"Master线程 "<<name<<" 唤醒一个线程......"<<std::endl;
        pthread_cond_broadcast(&gcond);//发送信号量，唤醒所有等待的线程
        std::cout<<"Master线程 "<<name<<" 唤醒所有线程......"<<std::endl;
        sleep(1);
    }
}

void StartMaster(std::vector<pthread_t> *tidsptr)
{
    pthread_t tid;
    int n=pthread_create(&tid,nullptr,MasterCore,(void*)"Master Thread");
    if(n==0)
    {
        std::cout<<"Create master Success"<<std::endl;  
    }
    tidsptr->emplace_back(tid);
}

void StartSlaver(std::vector<pthread_t> *tidsptr,int threadnum=3)
{
    for(int i=0;i<threadnum;i++)
    {
        char *name=new char[64];
        snprintf(name,64,"Slaver Thread %d",i+1);
        pthread_t tid;
        int n=pthread_create(&tid,nullptr,SlaverCore,(void*)name);
        if(n==0)
        {
            std::cout<<"Create slaver Success"<<std::endl;
            tidsptr->emplace_back(tid);
        }
        
    }
}

void WaitThread(std::vector<pthread_t> &tids)
{
    for(auto &tid:tids)
    {
        pthread_join(tid,nullptr);
    }
}

int main()
{
    std::vector<pthread_t> tids;
    StartMaster(&tids);
    StartSlaver(&tids,5);
    WaitThread(tids);
    return 0;
}